package com.ctz.commonframe.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;


public class CommonUtil {
    public static final int REQUEST_CODE_READ_PHONE_STATE = 1;

	/**
	 * 通过反射获得将要打开的activity
	 * 
	 * @param context 上下文
	 * @param className 要启动的Activity的类名
	 */
	public static void startActivity(Context context, String className) {
		try {
			Class<?> clazz = Class.forName(className);
			Intent intent = new Intent(context, clazz);
			context.startActivity(intent);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 换算文件大小的单位，够1024就进位
	 * 
	 * @param fileSize 文件size，单位为K
	 * @return 文件大小字符串，单位为K或M或G
	 */
	public static String convertFileSize(String fileSize) {
		float num = Float.parseFloat(String.valueOf(fileSize)) / 1024;
		DecimalFormat format = new DecimalFormat("##0.00");
		String size = format.format(num) + "K";
		if (num > 1024) {
			num = num / 1024;
			size = format.format(num) + "M";
			if (num / 1024 > 1024) {
				num = num / 1024;
				size = format.format(num) + "G";
			}
		}
		return size;
	}

	/**
	 * 字符串是否手机号码
	 *
	 * @param str 源字符串
	 * @return true为手机号码，否则false
	 */
	public static boolean isMobileNumber(String str){
		String regex = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
		Pattern pattern = Pattern.compile(regex);
		Matcher m = pattern.matcher(str);
		return m.find();
	}

    /**
     * 字符串是否座机号码
     *
     * @param str 源字符串
     * @return true为座机号码，否则false
     */
	public static boolean isPhoneNumber(String str){
		if(str == null) return false;
		boolean result;
		String regexWithAreaCode = "^[0][1-9]{2,3}-[0-9]{5,10}$";
		String regexWithNoAreaCode = "^[1-9][0-9]{5,8}$";
        Pattern p1 = Pattern.compile(regexWithAreaCode);  // 验证带区号的  
        Pattern p2 = Pattern.compile(regexWithNoAreaCode);  // 验证没有区号的  
        if(str.length() >9) {   
        	result = p1.matcher(str).matches();  
        }else{  
        	result = p2.matcher(str).matches();  
        }    
        return result; 
	}
	
	/**
     * 获取IMEI码
     */
    @SuppressLint("HardwareIds")
    public static String getIMEI(Activity context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if ( tm == null )
            return null;
        if ( Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1 ) {
            int permissionCheck = context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
            if ( permissionCheck != PackageManager.PERMISSION_GRANTED) {
                context.requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_CODE_READ_PHONE_STATE);
                return null;
            }else{
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
                    return tm.getImei();
                }
            }
        }
        return tm.getDeviceId();
    }

    /**
     * 从assets目录中获取文件字符串
     * @param context 上下文
     * @param fileName 文件名
     * @return 文件字符串
     */
	public static String getAssetsFile(Context context, String fileName) {
		try {
			InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
			BufferedReader bufReader = new BufferedReader(inputReader);
            StringBuilder result = new StringBuilder();
			String line;
			while ((line = bufReader.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
		} catch (Exception e) {
			Logger.e("getFromAssets failure:" + e.getLocalizedMessage());
		}
		return null;
	}

    /**
     * 进程是否存在
     * @param context 上下文
     * @param packageName 包名
     * @return true存在，false已被杀死
     */
	public static boolean isProcessAlive(Context context, String packageName){
		if (TextUtils.isEmpty(packageName) || context == null)
			return false;

		ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
		if (activityManager == null)
		    return false;
		if (activityManager.getRunningAppProcesses() == null)
		    return false;
		for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
			if (appProcess.processName.equals(packageName)) {
				return true;
			}
		}
		return false;
	}
} 

